<template>
  <div class="adopt-form-container">
    <el-card class="form-card" shadow="hover">
      <!-- 返回导航 -->
      <div class="nav-bar">
        <el-page-header @back="$router.back()">
          <template #content>
            <span class="page-title">申请领养</span>
          </template>
        </el-page-header>
      </div>

      <!-- 动物信息卡片 -->
      <el-card v-if="animal" class="animal-info-card" shadow="never">
        <div class="animal-preview">
          <div class="animal-image">
            <img :src="animal.photo" :alt="animal.name" />
          </div>
          <div class="animal-details">
            <h3 class="animal-name">
              <el-icon><Star /></el-icon>
              {{ animal.name || '未命名' }}
            </h3>
            <div class="animal-tags">
              <el-tag type="info">{{ animal.species }}</el-tag>
              <el-tag type="info">{{ animal.gender }}</el-tag>
              <el-tag :type="getStatusType(animal.status)">
                {{ getStatusText(animal.status) }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 领养表单 -->
      <el-card class="form-content-card" shadow="never">
        <h3 class="form-title">
          <el-icon><Document /></el-icon>
          领养申请信息
        </h3>

        <el-form 
          :model="form" 
          :rules="formRules" 
          ref="formRef"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="申请人姓名" prop="applicantName">
            <el-input 
              v-model="form.applicantName" 
              placeholder="请输入您的姓名"
              clearable
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入联系电话"
              clearable
              maxlength="11"
            />
          </el-form-item>

          <!-- <el-form-item label="身份证号" prop="idCard">
            <el-input 
              v-model="form.idCard" 
              placeholder="请输入身份证号"
              clearable
              maxlength="18"
            />
          </el-form-item> -->

          <el-form-item label="居住地址" prop="address">
            <el-input 
              v-model="form.address" 
              placeholder="请输入详细居住地址"
              clearable
            />
          </el-form-item>

          <el-form-item label="住房情况" prop="housingType">
            <el-select 
              v-model="form.housingType" 
              placeholder="请选择住房情况"
              clearable
              style="width: 100%"
            >
              <el-option label="自有住房" value="自有住房" />
              <el-option label="租房" value="租房" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>

          <el-form-item label="家庭成员" prop="familyMembers">
            <el-input 
              v-model="form.familyMembers" 
              placeholder="请输入家庭成员情况"
              clearable
            />
          </el-form-item>

          <el-form-item label="领养理由" prop="reason">
            <el-input 
              type="textarea" 
              v-model="form.reason" 
              :rows="5"
              placeholder="请详细说明您想领养此动物的理由，以及您能为它提供的照顾..."
              maxlength="999"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="养宠经验" prop="experience">
            <el-input 
              type="textarea" 
              v-model="form.experience" 
              :rows="4"
              placeholder="请说明您是否有养宠经验，如果有，请简要描述..."
              maxlength="999"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="large" @click="submitForm" :loading="submitting">
              <el-icon><Check /></el-icon>
              提交申请
            </el-button>
            <el-button size="large" @click="goBack">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import { Star, Document, Check } from '@element-plus/icons-vue';

export default {
  components: {
    Star,
    Document,
    Check
  },
   data() {
     // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      animal: null,
      submitting: false,
       form: {
         userId: null,
         animalId: null,
         applicantName: '',
         phone: '',
         address: '',
         housingType: '',
         familyMembers: '',
         reason: '',
         experience: ''
       },
      formRules: {
        applicantName: [
          { required: true, message: '请输入申请人姓名', trigger: 'blur' }
        ],
         phone: [
           { required: true, validator: validatePhone, trigger: 'blur' }
         ],
         address: [
          { required: true, message: '请输入居住地址', trigger: 'blur' },
          { min: 5, message: '地址至少5个字符', trigger: 'blur' }
        ],
        housingType: [
          { required: true, message: '请选择住房情况', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入领养理由', trigger: 'blur' },
          { min: 300, message: '领养理由至少300个字', trigger: 'blur' }
        ],
        experience: [
          { required: true, message: '请输入养宠经验', trigger: 'blur' },
          { min: 300, message: '养宠经验至少300个字', trigger: 'blur' }
        ]
      }
    };
  },
  async mounted() {
    const animalId = this.$route.params.id;
    const userId = localStorage.getItem('userId');
    
    this.form.animalId = animalId;
    this.form.userId = userId;

    // 加载动物信息
    try {
      const res = await axios.get(`http://localhost:8080/api/animal/detail/${animalId}`);
      if (res.data.code === 200) {
        this.animal = res.data.data.animal;
      } else {
        ElMessage.error('加载动物信息失败');
        this.$router.back();
      }
    } catch (error) {
      ElMessage.error('加载动物信息失败');
      this.$router.back();
    }
  },
  methods: {
    getStatusText(status) {
      const statusTexts = [ "待领养", "已领养"];
      return statusTexts[status] || '未知';
    },
    getStatusType(status) {
      const types = ['warning', 'info', 'success', 'info'];
      return types[status] || 'info';
    },
    async submitForm() {
      if (!this.$refs.formRef) return;

      await this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请完善表单信息');
          return;
        }

        this.submitting = true;
        try {
          const res = await axios.post('http://localhost:8080/api/adoption/apply', this.form);
          
          if (res.data.code === 200) {
            ElMessage.success('申请提交成功！我们会尽快审核您的申请');
            setTimeout(() => {
              // 跳转回动物详情页，并传递refresh参数触发刷新
              this.$router.push({
                path: `/user/animal/${this.form.animalId}`,
                query: { refresh: Date.now() }
              });
            }, 1500);
          } else {
            ElMessage.error(res.data.msg || '提交失败');
          }
        } catch (error) {
          ElMessage.error('提交失败：' + (error.message || '网络错误'));
        } finally {
          this.submitting = false;
        }
      });
    },
    goBack() {
      this.$router.back();
    }
  }
};
</script>

<style scoped>
.adopt-form-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

.form-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 12px;
}

.nav-bar {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

/* 动物信息卡片 */
.animal-info-card {
  margin-bottom: 20px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.animal-info-card .el-card__body) {
  padding: 20px;
}

.animal-preview {
  display: flex;
  align-items: center;
  gap: 20px;
}

.animal-image {
  flex-shrink: 0;
  width: 120px;
  height: 120px;
  border-radius: 12px;
  overflow: hidden;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.animal-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.animal-details {
  flex: 1;
}

.animal-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
}

.animal-name .el-icon {
  font-size: 28px;
  color: #ffd700;
}

.animal-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.animal-tags :deep(.el-tag) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-weight: 500;
}

/* 表单内容卡片 */
.form-content-card {
  border-radius: 12px;
}

.form-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 0 24px 0;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-title .el-icon {
  font-size: 24px;
  color: #409eff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-select) {
  width: 100%;
}

.el-button {
  margin-right: 12px;
}

.el-button--large {
  padding: 12px 28px;
  font-weight: 500;
}

/* 响应式 */
@media (max-width: 768px) {
  .adopt-form-container {
    padding: 10px;
  }

  .animal-preview {
    flex-direction: column;
    text-align: center;
  }

  .animal-image {
    width: 100px;
    height: 100px;
  }

  .form-title {
    font-size: 18px;
  }
}
</style>

